const HandAccount = require('../models/handAccount')

class HandAccountCtl{
    async find(ctx){
        const { limit = 10 } = ctx.query;
        const perPage = Math.max(limit * 1, 1);
        const page = Math.max(ctx.query.page * 1 -1, 0)
        const title = new RegExp(ctx.query.title)
        ctx.body = await HandAccount.find({$or: [{title}]})
            .limit(perPage)
            .skip(page*perPage)
    }

    async findById(ctx){
        const handAccount = await HandAccount.findById(ctx.params.id).populate('owner topic')
        if(!handAccount) ctx.throw(404, '手账不存在')
        ctx.body = handAccount
    }

    async create(ctx){
        const {content, owner, topic, isOpen, title} = ctx.request.body
        let handAccount = {
            content,
            owner,
            topic,
            title,
            isOpen
        }
        ctx.body = await new HandAccount(handAccount).save()
    }

    // 更新手账
    async update(ctx){
        await ctx.state.handAccount.update(ctx.request.body)
        ctx.body = {}
    }

    // todo 接口的安全判断
    async checkOwner(ctx, next){
        const { handAccount } = ctx.state
        if(handAccount.owner.toString() !== ctx.state.user._id) ctx.throw(403, '没有权限')
        await next()
    }

    async delete(ctx){
        ctx.status = 204
        await HandAccount.findByIdAndRemove(ctx.params.id)
    }

    // 检查手帐是否存在中间件
    async checkHandAccountExist(ctx, next){
        const handAccount = HandAccount.findById(ctx.params.id).select('+woner')
        if(!handAccount) ctx.throw(404, '手帐不存在')
        ctx.state.handAccount = handAccount
        await next()
    }

    // 点赞
    async like(ctx){
        const me = await User.findById(ctx.state.user._id).select('+following')
        if(!me.following.map(id=>id.toString()).includes(ctx.params.id)){
            me.following.push(ctx.params.id).save()
        }
        ctx.status = 204         
    }
    // 取消点赞
    async unlike(ctx){
        const me = await User.findById(ctx.state.user._id).select('+following')
        const index = me.following.map(id=>id.toString()).indexOf(ctx.params.id)
        if(index > -1){
            me.following.splice(index, 1).save()
        }
        ctx.status = 204       
    }
}

module.exports = new HandAccountCtl()